package org.apache.click.doubleclick.injectspring;

import org.apache.click.Context;
import org.apache.click.Page;
import org.apache.click.doubleclick.inject.ContextResolver;
import org.apache.commons.lang.Validate;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;

public class SpringContextResolverImpl<T extends ApplicationContext> implements ContextResolver<T> {
    /**
     * {@inheritDoc}
     */
    @Override
    public T resolveDependencyInjectorContext() {
        Validate.isTrue(Context.hasThreadLocalContext(), "Thread local context is not available");
        ServletContext servletContext = Context.getThreadLocalContext().getServletContext();
        Validate.notNull(servletContext, "Servlet context is null");
        return (T) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public T resolveDependencyInjectorContext(Page page) {
        Validate.notNull(page, "Page can not be null while resolving servlet context");
        ServletContext servletContext = page.getContext().getServletContext();
        return (T) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    }
}